import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {TicketService} from '../../../../services/api/ticket.service';
import {AlertComponent, DynamicComponent, DynamicComponentEvent} from '../../../../../ng-tools';
import {HttpParams} from '@angular/common/http';

@Component({
  selector: 'robot-group-item-config',
  templateUrl: './robot-group-item-config.component.html',
  styleUrls: ['./robot-group-item-config.component.scss']
})
export class RobotGroupItemConfigComponent implements OnInit, DynamicComponent {
  configForm: FormGroup;
  context: any;
  dynamic: true;
  events: DynamicComponentEvent;
  currentGroup;
  alterOption = {
    theme: 'success',
    data: '',
    position: 'center'
  };
  @ViewChild('alert') private alert: AlertComponent;
  set data(value: any) {
    this.currentGroup = value;
  }
  @Output() success = new EventEmitter();
  constructor(private formBuilder: FormBuilder,
              private ticketService: TicketService) {
    this.configForm = this.formBuilder.group({
      id: ['', ],
      groupName: ['', Validators.required],
      autoSendAfterSeconds: ['', Validators.required],
      downTimes: ['', Validators.required],
      upTimes: ['', Validators.required],
      aotoSnatchRedAfterSeconds: ['', Validators.required],
      notDeadUserId: ['', Validators.required],
    });
  }

  ngOnInit() {
    if (this.currentGroup !== null && this.currentGroup !== undefined) {
      this.configForm.patchValue(this.currentGroup);
    }
  }

  save() {
    if (this.configForm.valid) {
      this.ticketService.post(this.ticketService.urls.createRobotGroup, this.configForm.value, {
        observe: 'response',
        params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
        if (resp.body.success) {
            this.trigger('success');
          } else {
          this.alterOption.theme = 'danger';
          this.alterOption.data = resp.body.msg;
            this.alert.show(this.alterOption, 2000);
        }
      });
    }
  }

  trigger(eventName: string, ...args) {
    this[eventName].emit(...args);
    if (eventName in this.events) {
      this.events[eventName](...args);
    }
  }

}
